package com.attilax.rest;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;
//r44 import java.util.Optional;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.reflect.MethodUtils;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//import aaaCfg.IocX4nodb;


















import com.attilax.core;
import com.attilax.collection.list;
import com.attilax.dsl.DslParser;
//import com.attilax.dsl.DslParser;
import com.attilax.exception.ExUtil;
import com.attilax.hre.UrlDslParser;
import com.attilax.hre.UrlDslParserV2;
import com.attilax.io.filex;
import com.attilax.ioc.IocFacV3_iocx_iocutil;
import com.attilax.ioc.IocUtilV2;
import com.attilax.ioc.IocXq214;
import com.attilax.json.AtiJson;
import com.attilax.lang.Global;
import com.attilax.net.requestImp;
import com.attilax.ref.refx;
import com.attilax.up.FileUploadService;
import com.attilax.web.ReqX;
import com.attilax.web.UrlX;
import com.attilax.web.responseImp;
import com.attilax.wechat.Order;
import com.attilax.wechat.WeChatPayUtil;
import com.attilax.wrmi.JsnaInvoker;
import com.attilax.wrmi.Wrmi;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.Inject;

/** com.attilax.rest.Api
 * com.attilax.rest.DslAjaxJsbridge_HttpparamMode_servlet
 * com.attilax.order.RechargeOrderService jobus not use ,,can be game use ..
 * /CommonServlet?$method= com.attilax.up.FileUploadService.upload
 * 
 * /CommonServlet?$method= com.attilax.up.FileUploadService.process
 * 
 * @author Administrator
 * 
 *         / /jsnaServlet?$method=com.attilax.jsna.test.add&param1=2&param2=3
 *
 *         jeig he not support meth chain...deft use dyna new mode...
 *         v2 will add stati mode
 */
/**
 * for wash  @WebxxServlet   (name = "api_name", urlPatterns = "/api")
 * @author Administrator
 *
 */

public class Api implements Servlet {

	public static void main(String[] args) {
		System.setProperty("prj", "com.attilax.rest.JavaNewCreatorFac");
		System.setProperty("agent_cfgfile", "cfg_game.properties");
		System.out.println("2333");
		
		responseImp resImp=new responseImp();
		requestImp ri=new requestImp();
	//	ri.setParam("iocFac", "com.attilax.rest.JavaNewCreatorFac");
	//	ri.setParam("c", "");
		ri.setParam("m", "com.attilax.rest.Class4test.m1");
		ri.setParam("p1_type", "s");
		ri.setParam("p1", "select * from agt");
		new Api().service(ri, resImp);
		System.out.println("--f122");
		logger.error("--e44rr10");
		// org.apache.xmlbeans
		// org.apache.xmlbeans
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public ServletConfig getServletConfig() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getServletInfo() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void init(ServletConfig paramServletConfig) throws ServletException {

		// UrlDslParserx = IocXq214.getBean(UrlDslParser.class);

	}

	public static ThreadLocal<ServletResponse> resp = new ThreadLocal<ServletResponse>();

	@Inject
	UrlDslParser UrlDslParserx;
	private static boolean isBaseDateType(Object s) {
		if(s.getClass()==Integer.class)
			return true;
		if(s.getClass()==String.class)
			return true;
		 System.out.println( );
		return false;
	}
	@Override
	public void service(ServletRequest req, ServletResponse response) {
		try {
			HttpServletResponse res=(HttpServletResponse) response;
			res.setHeader("Access-Control-Allow-Origin", "*");
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=UTF-8");
			HttpServletRequest req2 = (HttpServletRequest) req;
			req.setCharacterEncoding("utf-8");
	//		req.se
			req2.setCharacterEncoding("utf-8");
			Global.req.set(req2);

			String iocx =get_iocFac( req.getParameter("iocFac"));
			String class_meth_full = (getMeth(req));
			
			
			String cls =refx.getClassName(class_meth_full);
			String meth_name=refx.getMethodName(class_meth_full);
		 
			Class c = Class.forName(cls);
		 
			
			List<Object> params = Lists.newArrayList();
			for (int i = 1; i < 7; i++) {
				String pname = "p" + i;
				if (req.getParameter(pname) == null)
					continue;

				String p = req.getParameter(pname);
		
				try {
					if(class_meth_full.trim().startsWith("com.attilax.db.DbServiceV4qb9") )
	 					p=UrlX.decode(p);
				} catch (Exception e) {
					  logger.warn("decode manul, pname:"+pname +"  ,pval:"+p) ;
				}
				  logger.info(" pname:"+pname +"  ,pval:"+p) ;
				String ptype = getPtype(req, pname);	
				Object p_obj=getP(p,ptype);
				params.add(p_obj);
				

			}
			
			Object[] p_a = params.toArray();
			String createmode =req.getParameter("createmode");
			Object rzt;
			if(isStaticMode(createmode))
			{
				rzt = MethodUtils.invokeStaticMethod(c, meth_name, p_a);
				
			}
			else//def is new
			{
				Object cls_obj = com.attilax.reflect.MethodUtils.invokeStaticMethod(iocx, "getBean", c);
				  rzt = MethodUtils.invokeMethod(cls_obj, meth_name, p_a);
			}
				
			
			
			System.out.println(rzt);
			// Object r = new DslParser().parseV3(req2.getParameter("dsl"));
			String retFmt = getRetFmt(req);

			if (retFmt!=null&& retFmt.trim().equals("json"))
				response.getWriter().println(AtiJson.toJson(rzt)); // �벻Ҫ�޸Ļ�ɾ��
			else if ( retFmt!=null&& retFmt.trim().equals("none"))
				response.getWriter().println(rzt.toString()); // �벻Ҫ�޸Ļ�ɾ��
			else if( (retFmt==null || retFmt.length()==0 )&& isBaseDateType(rzt))
				response.getWriter().println(rzt); 
			else //def  obj type
				response.getWriter().println(AtiJson.toJson(rzt));
		} catch (Exception e) {
			logger.error("--err", e);
			logger.error("--err2", AtiJson.toJson(e));
			filex.save_safe(core.getTrace(e), "c:\\0rechglog\\" + filex.getUUidName() + ".log");
			ExUtil.throwExV2(e);
		}

	}

	private String getRetFmt(ServletRequest req) {
//		if (req.getParameter("retFmt") == null || req.getParameter("retFmt").trim().equals("") ) 
//		return "json";
//		else
			return	req.getParameter("retFmt");
	}

	private boolean isStaticMode(String createmode) {
		if(createmode==null  )
			
			return false;
			if(createmode.trim().length()==0)
				return false;
			if(createmode.trim().equals("static"))
				return true;
		//	if(createmode.trim().equals("static"))
		//	return this;
		//	throw new RuntimeException("ille create mode");
			return false;  //def
	 
	}

	private String getClassStr(ServletRequest req) {
		 
		 String m;
		if( req.getParameter("class")!=null  )
			return  req.getParameter("class").trim();
		// method is null
		try {
			return req.getParameter("c").trim();
		} catch (Exception e) {
			 throw new RuntimeException(" m param is illege");
		}
	}

	private String getMeth(ServletRequest req) {
		
		if(req.getParameter("method")!=null&& req.getParameter("method").trim().toLowerCase().equals("q")  )
			return "com.attilax.db.DbServiceV4qb9.executeQuery";
		if(req.getParameter("m")!=null&& req.getParameter("m").trim().toLowerCase().equals("q")  )
			return "com.attilax.db.DbServiceV4qb9.executeQuery";
		
		if(req.getParameter("m")!=null&& req.getParameter("m").trim().toLowerCase().equals("qm")  )
			return "com.attilax.db.DbServiceV4qb9.executeQuery_multisql";
		
		
		
		if(req.getParameter("method")!=null&& req.getParameter("method").trim().toLowerCase().equals("u")  )
			return "com.attilax.db.DbServiceV4qb9.executeUpdate";
		if(req.getParameter("m")!=null&& req.getParameter("m").trim().toLowerCase().equals("u")  )
			return "com.attilax.db.DbServiceV4qb9.executeUpdate";
		 String m;
		if( req.getParameter("method")!=null  )
			return  req.getParameter("method").trim();
		// method is null
		try {
			return req.getParameter("m").trim();
		} catch (Exception e) {
			 throw new RuntimeException(" m param is illege");
		}
			
		
	  
	}

	private String get_iocFac(String parameter) {
	   if(parameter==null || parameter.trim().equals(""))
		return "com.attilax.ioc.Ioc4wash";
		return parameter.trim();
	}

	private boolean isNewMode(String createmode) {
		 
		if(createmode==null  )
			
		return false;
		if(createmode.trim().length()==0)
			return false;
		if(createmode.trim().equals("new"))
			return true;
	//	if(createmode.trim().equals("static"))
	//	return this;
	//	throw new RuntimeException("ille create mode");
		return false;  //def
	}

	private Object getP(String p, String ptype) {
		if (ptype.equals("s") || ptype.equals("str")) {
			 return p;
		} else if (ptype.equals("opt")&& p.equals("$empty")) {
			 
				return (Optional.absent());
		}
		else if (ptype.equals("opt<map>")){
			Map m=Maps.newConcurrentMap();
			String[] a=p.split(",");
			for (String kv : a) {
				String[] kv_item=kv.split(":");
				m.put(kv_item[0],kv_item[1]);
			}
			return (Optional.of(m));
			 
		}
		throw new RuntimeException("getP.ex");
	}

	private String getPtype(ServletRequest req, String pname) {
		String ptype = req.getParameter(pname + "_type");
		if (ptype == null)
			ptype = "str";
		else if (ptype.length()==0)
			ptype = "str";
		return ptype;
	}

	public static final Logger logger = LoggerFactory.getLogger(Api.class);

}
